package com.pz.cloud.framework.workflow.config;

import com.pz.cloud.framework.workflow.listener.TaskCompleteListener;
import com.pz.cloud.framework.workflow.listener.TaskCreateListener;
import org.activiti.engine.*;
import org.activiti.engine.delegate.event.ActivitiEventListener;
import org.activiti.spring.ProcessEngineFactoryBean;
import org.activiti.spring.SpringProcessEngineConfiguration;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.transaction.PlatformTransactionManager;

import javax.sql.DataSource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
@Configuration
public class WorkflowConfig {

    @Autowired
    private DataSource dataSource;

    @Autowired
    private PlatformTransactionManager platformTransactionManager;

    @Bean
    public SpringProcessEngineConfiguration springProcessEngineConfiguration(){
        SpringProcessEngineConfiguration spec = new SpringProcessEngineConfiguration();
        spec.setDataSource(dataSource);
        spec.setTransactionManager(platformTransactionManager);
        spec.setDatabaseSchemaUpdate("true");


        /**
         * 监听器
         */
        Map<String, List<ActivitiEventListener>> typedEventListeners = new HashMap<>();
        List<ActivitiEventListener> createdListeners = new ArrayList<>();
        createdListeners.add(new TaskCreateListener());
        List<ActivitiEventListener> completeListeners = new ArrayList<>();
        completeListeners.add(new TaskCompleteListener());
        typedEventListeners.put("TASK_CREATED",createdListeners);
        typedEventListeners.put("TASK_COMPLETED",completeListeners);
        spec.setTypedEventListeners(typedEventListeners);
        return spec;
    }

    @Bean
    public ProcessEngineFactoryBean processEngineFactoryBean(){
        ProcessEngineFactoryBean processEngineFactoryBean = new ProcessEngineFactoryBean();
        processEngineFactoryBean.setProcessEngineConfiguration(springProcessEngineConfiguration());
        return processEngineFactoryBean;
    }

    @Bean
    public ProcessEngine processEngine() throws Exception {
        return processEngineFactoryBean().getObject();
    }


    @Bean
    public RepositoryService repositoryService() throws Exception{
        return processEngine().getRepositoryService();
    }
    @Bean
    public RuntimeService runtimeService() throws Exception{
        return processEngine().getRuntimeService();
    }
    @Bean
    public TaskService taskService() throws Exception{
        return processEngine().getTaskService();
    }
    @Bean
    public HistoryService historyService() throws Exception{
        return processEngine().getHistoryService();
    }

    @Bean
    public IdentityService identityService() throws Exception {
        return processEngine().getIdentityService();
    }

}
